﻿using Framework.EncryptionDecryptionService.Abstract;
using Framework.EncryptionDecryptionService.Attributes;
using Framework.EncryptionDecryptionService.Enums;
using Framework.EncryptionDecryptionService.Helpers;
using Framework.EncryptionDecryptionService.Inteface;
using System.Security.Cryptography;

namespace Framework.EncryptionDecryptionService.Achieve
{
    /// <summary>
    /// AES加密服务
    /// </summary>
    /// <remarks>
    /// 使用方式：
    /// <para>1、注入：通过注入获取到的AES加密服务生命周期跟随API的生命周期，且AES秘钥在整个API的生命周期内不变</para>
    /// <para>2、实例：通过实例生成的AES加密服务周期为当前实例的生命周期，此时AES秘钥需要重新生成，且秘钥生命周期与实例AES加密服务生命周期一致</para>
    /// </remarks>
    [Encryption(EncryptionAlgorithm.AES)]
    public sealed class EncryptionServiceAes : AbsEncryptionService
    {
        /// <summary>
        /// AES加密服务
        /// </summary>
        /// <param name="secretKey">AES秘钥</param>
        /// <remarks>实例：通过实例生成的AES加密服务周期为当前实例的生命周期，此时AES秘钥需要重新生成，且秘钥生命周期与实例AES加密服务生命周期一致</remarks>
        public EncryptionServiceAes(SecretKeyServiceAes secretKey = null) : base(secretKey ?? new SecretKeyServiceAes())
        {
        }

        public override byte[] Encrypt(string data)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = SecretKey.PrivateSecretKey.FromBase64String();
                aes.IV = SecretKey.PublicSecretKey.FromBase64String();
                ICryptoTransform cryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(data);
                        }
                        return ms.ToArray();
                    }
                }
            }
        }
    }
}
